package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @Author: taft
 * @Date: 2018-12-18 9:11
 */
@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    public PageResult<Brand> queryBrandByPage(Integer page, Integer rows,String sortBy,Boolean desc,String key) {

        //开启分页
        PageHelper.startPage(page,rows);

        Example example = new Example(Brand.class);

        Example.Criteria criteria = example.createCriteria();

        //拼接动态sql
        if (StringUtils.isNotBlank(key)){
            criteria.andEqualTo("letter",key);
        }


        //判断是否有排序条件
        if (StringUtils.isNotBlank(sortBy)){
           example.setOrderByClause(sortBy +(desc ? " DESC":" ASC")); //相当于写好了order by 只需要加入排序字段以及排序方式　例如:order by id desc
        }

        Page<Brand> brandPage = (Page<Brand>) this.brandMapper.selectByExample(example);

        return new PageResult<>(brandPage.getTotal(),new Long(brandPage.getPages()),brandPage);
    }

    @Transactional
    public void saveBrand(Brand brand, List<Long> cids) {
        //保存后主键回显
        this.brandMapper.insertSelective(brand);

        //循环保存分类和品牌的关系
        cids.forEach(cid-> this.brandMapper.insertCategoryBrand(cid,brand.getId()));


    }

    @Transactional
    public void updateBrand(Brand brand, List<Long> cids) {

        this.brandMapper.updateByPrimaryKeySelective(brand);

        //先删除原来的分类关系
        this.brandMapper.deleteAllByBrandId(brand.getId());

        //循环保存分类和品牌的关系
        cids.forEach(cid-> this.brandMapper.insertCategoryBrand(cid,brand.getId()));

    }

    public Brand getBrandById(Long brandId) {
        return this.brandMapper.selectByPrimaryKey(brandId);
    }

    public List<Brand> queryBrandByCategory(Long cid) {
        return this.brandMapper.queryBrandByCategory(cid);
    }

    public List<Brand> getBrandsByIds(List<Long> bids) {
        return this.brandMapper.selectByIdList(bids);
    }
}
